/*
 * HandleRefCount.cpp
 *
 *  Created on: 2023年2月21日
 *      Author: terry
 */

#include "HandleRefCount.h"

HandleRefCount::HandleRefCount()
{
}

HandleRefCount::~HandleRefCount()
{
}


bool HandleRefCount::empty()
{
    return count() == 0;
}

size_t HandleRefCount::count()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_handles.size();
}

bool HandleRefCount::exists(void* handle)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    HandleSet::const_iterator it = m_handles.find(handle);
    return it != m_handles.end();
}

bool HandleRefCount::add(void* handle)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    bool inserted = m_handles.insert(handle).second;
    return inserted;
}

bool HandleRefCount::remove(void* handle)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_handles.erase(handle) > 0;
}

HandleRefCount::HandleArray HandleRefCount::getHandles()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    HandleArray handles;
    for (void* handle : m_handles)
    {
    	handles.push_back(handle);
    }
    return handles;
}

void HandleRefCount::clear()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_handles.clear();
}
